package com.boot.controller;

import com.boot.entity.User;
import com.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class LoginController {

    @Autowired
    UserService userService;

    @GetMapping("/login")
    public String login(){
        return "user/login";
    }

    @GetMapping("/register")
    public String register(){
        return "user/register";
    }

    @GetMapping("/doLogin")
    @ResponseBody //不会返回到页面 而是直接响应文本
    public String doLogin(HttpSession session, HttpServletResponse response, String userName, String password) throws IOException {

        User user = userService.login(userName,password);

        if(user!=null){
            session.setAttribute("user",user);
            Cookie cookie = new Cookie("userId",user.getId().toString());
            cookie.setMaxAge(24 * 60 * 60 * 30);//一个月
            cookie.setPath("/");
            response.addCookie(cookie);

            return "success";

        }else{
            return "error";
        }
    }

    @PostMapping("/doRegister")
    public String doRegister(String userName,String password){
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        userService.saveOrUpdate(user);

        return "redirect:/user/login";
    }

    @GetMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/user/login";
    }

}
